
package com.gcloud.mesh.monitor.timer;

import java.util.Timer;
import java.util.TimerTask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * 
   * @Date 2016-7-12
   *
   * @Author dengxiaoming@gcloudtech.com
   *
   * @Copyright 2016 www.gcloudtech.com Inc. All rights reserved.
   *
   * @Description 定时器基类
 */

public abstract class BaseTimer implements ITimer {

    static Logger LOG = LoggerFactory.getLogger(BaseTimer.class);

    private boolean active = false;

    private Timer timer;

    /**
     * 定时执行的逻辑代码的任务类
     * @return 定时执行的逻辑代码的任务类
     */
    private TimerTask getTimerTask() {
        return new TimerTask() {

            @Override
            public void run() {
                try {
                    process();
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }

    public abstract void process();

    @Override
    public boolean init() {
        return true;
    }

    @Override
    public void start() {
        if (!this.active) {
            timer = new Timer();
            timer.schedule(this.getTimerTask(), this.getDelay(), this.getRate());
            this.active = true;
            LOG.info("timer started");
        }
        else {
            LOG.info("timer is already started");
        }
    }

    @Override
    public void stop() {
        if (this.active) {
            timer.cancel();
            timer = null;
            this.active = false;
            LOG.info("timer stopped");
        }
        else {
            LOG.info("timer is already stopped");
        }
    }

    @Override
    public long getDelay() {
        return 20 * 1000L;
    }

    @Override
    public long getRate() {
        return 60 * 1000;
    }

    @Override
    public boolean autoStart() {
        return true;
    }

}
